package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.reids.subpub.RedisReliableMessageSubPub;
import com.yanqu.road.reids.subpub.eRedisChannelType;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 37论坛签到
 */
@WebServlet(urlPatterns = "/platformLunTanSignIn")
public class PlatformLunTanSignIn extends BaseJsonHttpServlet {

    private static Logger logger = LogManager.getLogger(PlatformLunTanSignIn.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("request platformLunTanSignIn");
        HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
        JSONObject paramObj = httpJsonWebParam.getParamObj();
        String platformUserId;
        String source_platform;
        try{
            platformUserId = paramObj.getString("uid");
            source_platform = paramObj.getString("source_platform");
        }catch (Exception e){
            logger.error("platformLunTanSignIn argument error:" + e);
            sendResult(response, 0, "argument error");
            return;
        }
        if(WebServer.getInstance().isNeedSend() && Objects.equals(source_platform, "201")){
            // 转发消息到对应的服务器上
            String result = HttpHelper.doPostJson(ChannelConfig.LOGIN_SEND_URL + "platformLunTanSignIn", paramObj.toJSONString(), "UTF-8");
            sendMessage(response, result);
            return;
        }
        int today = Integer.valueOf(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
        String message = platformUserId + ";" + today;
        long publish = RedisReliableMessageSubPub.getInstance().publish(eRedisChannelType.LunTanSignIn, message);
        if(publish == 0){
            logger.error("platformLunTanSignIn publish fails, {},{}", platformUserId, source_platform);
        }
        sendResult(response, 1, "success");
    }
}
